package com.example.service.impl;

import com.example.mapper.ArticleMapper;
import com.example.pojo.Article;
import com.example.pojo.PageBean;
import com.example.service.ArticleService;
import com.example.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    //    新增文章
    @Override
    public void add(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        articleMapper.add(article);

    }

    //条件分页列表查询
    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
//        1.创建pagebean对象
        PageBean<Article> pb = new PageBean<>();
//        2.开启分页查询 pageHelper
        PageHelper.startPage(pageNum, pageSize);
//        3.调用mapper 于获取当前登录用户的新闻
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
//        查询到的所有数据
        List<Article> as= articleMapper.list(userId,categoryId,state);
//        强转成pagehelper ,page提供了方法，可以获取pagehelper分页查询后，得到的总记录数和当前页数据
        Page<Article> p=(Page<Article>) as;
//        把数据填充到pagebean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
    //获取文章详情
    @Override
    public Article findById(Integer id) {
       Article article= articleMapper.findById(id);
        return article;
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);

    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }


}
